/**
 * Created with IntelliJ IDEA.
 * User: Hkkkk Guo
 * Date: 2023/2/10
 * Time: 12:15
 * Description:
 */
package com.hangkai.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hangkai.reggie.common.Result;
import com.hangkai.reggie.domain.Category;
import com.hangkai.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;
    /**
     * 添加分类
     * @param category
     * @return
     */
    @PostMapping
    public Result<String> addCategory(@RequestBody Category category){
        categoryService.save(category);
        return Result.success("新增分类成功");
    }

    /**
     * 打开页面 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public Result<Page<Category>> getCategoryPage(int page, int pageSize){

        //分页构造器
        Page<Category> pageInfo = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();

        //排序条件
        lqw.orderByAsc(Category::getSort);
        categoryService.page(pageInfo, lqw);
        return Result.success(pageInfo);
    }

    /**
     * 删除分类
     * @param id
     * @return
     */
    @DeleteMapping
    public Result<String> deleteCategory(Long id){
        log.info("删除分类 {}", id);
        categoryService.remove(id);
        return Result.success("删除成功!");
    }

    /**
     * 修改分类
     * @param category
     * @return
     */
    @PutMapping
    public Result<String> updateCategory(@RequestBody Category category){
        log.info("修改法分类信息 {}", category.toString());
        categoryService.updateById(category);
        return Result.success("修改分类成功");
    }

    /**
     * 根据条件查询分类数据
     * @param category
     * @return
     */
    @GetMapping("/list")
    public Result<List<Category>> getDishCategory(Category category){
        //条件构造器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        //根据type来查询
        lqw.eq(category.getType()!=null, Category::getType, category.getType());
        //添加排序条件
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = categoryService.list(lqw);
        return Result.success(list);
    }
}
